<template>
  <div class="profile-management">
    <el-row :gutter="20">
      <!-- 左侧：个人信息编辑 -->
      <el-col :span="16">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <h3>个人信息</h3>
              <el-button type="primary" @click="saveProfile" :loading="saving">保存修改</el-button>
            </div>
          </template>

          <el-form ref="profileFormRef" :model="profileForm" :rules="profileRules" label-width="100px">
            <!-- 头像上传 -->
            <el-form-item label="头像" prop="avatarUrl">
              <div class="avatar-upload">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadAction"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :on-error="handleAvatarError"
                  :before-upload="beforeAvatarUpload"
                  name="file"
                >
                  <img v-if="profileForm.avatarUrl" :src="getAvatarUrl(profileForm.avatarUrl)" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <div class="avatar-tips">
                  <p>点击上传头像</p>
                  <p class="tips-text">支持 JPG、PNG 格式，文件大小不超过 2MB</p>
                </div>
              </div>
            </el-form-item>

            <!-- 用户名 -->
            <el-form-item label="用户名" prop="username">
              <el-input v-model="profileForm.username" disabled>
                <template #suffix>
                  <el-tooltip content="用户名不可修改" placement="top">
                    <el-icon><InfoFilled /></el-icon>
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>

            <!-- 真实姓名 -->
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="profileForm.realName" placeholder="请输入真实姓名" />
            </el-form-item>

            <!-- 手机号 -->
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
            </el-form-item>

            <!-- 身份证号 -->
            <el-form-item label="身份证号" prop="idCard">
              <el-input
                v-model="profileForm.idCard"
                placeholder="请输入身份证号"
                @focus="handleIdCardFocus"
                @blur="handleIdCardBlur"
              >
                <template #suffix>
                  <el-button
                    v-if="!isEditingIdCard && profileForm.idCard"
                    type="text"
                    size="small"
                    @click="editIdCard"
                  >
                    编辑
                  </el-button>
                </template>
              </el-input>
            </el-form-item>

            <!-- 驾驶证号 -->
            <el-form-item label="驾驶证号" prop="driverLicense">
              <el-input
                v-model="profileForm.driverLicense"
                placeholder="请输入驾驶证号"
                @focus="handleDriverLicenseFocus"
                @blur="handleDriverLicenseBlur"
              >
                <template #suffix>
                  <el-button
                    v-if="!isEditingDriverLicense && profileForm.driverLicense"
                    type="text"
                    size="small"
                    @click="editDriverLicense"
                  >
                    编辑
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧：资料完整性和安全信息 -->
      <el-col :span="8">
        <!-- 资料完整性 -->
        <el-card class="completeness-card" style="margin-bottom: 20px;">
          <template #header>
            <h4>资料完整性</h4>
          </template>
          
          <div class="completeness-content">
            <div class="progress-section">
              <el-progress 
                :percentage="completenessInfo.completeness" 
                :color="getProgressColor(completenessInfo.completeness)"
                :stroke-width="8"
              />
              <p class="progress-text">
                已完成 {{ completenessInfo.completedFields || 0 }}/{{ completenessInfo.totalFields || 6 }} 项
              </p>
            </div>

            <div v-if="completenessInfo.missingFields && completenessInfo.missingFields.length > 0" class="missing-fields">
              <h5>待完善信息：</h5>
              <ul>
                <li v-for="field in completenessInfo.missingFields" :key="field">{{ field }}</li>
              </ul>
            </div>

            <div v-if="suggestions.length > 0" class="suggestions">
              <h5>完善建议：</h5>
              <div v-for="suggestion in suggestions" :key="suggestion.field" class="suggestion-item">
                <el-tag :type="getSuggestionType(suggestion.priority)" size="small">
                  {{ suggestion.title }}
                </el-tag>
                <p class="suggestion-desc">{{ suggestion.description }}</p>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 账户安全 -->
        <el-card class="security-card">
          <template #header>
            <h4>账户安全</h4>
          </template>
          
          <div class="security-content">
            <div class="security-level">
              <span>安全等级：</span>
              <el-tag :type="getSecurityType(securityInfo.securityLevel)">
                {{ securityInfo.securityLevelText || '未知' }}
              </el-tag>
            </div>

            <div class="security-items">
              <div class="security-item">
                <span>登录密码</span>
                <el-button type="text" @click="$router.push('/user/profile/changePassword')">修改</el-button>
              </div>
              <div class="security-item">
                <span>手机号</span>
                <span class="security-value">{{ securityInfo.phone || '未绑定' }}</span>
              </div>
              <div class="security-item">
                <span>实名认证</span>
                <el-tag v-if="securityInfo.hasIdCard" type="success" size="small">已认证</el-tag>
                <el-tag v-else type="info" size="small">未认证</el-tag>
              </div>
              <div class="security-item">
                <span>驾驶证认证</span>
                <el-tag v-if="securityInfo.hasDriverLicense" type="success" size="small">已认证</el-tag>
                <el-tag v-else type="info" size="small">未认证</el-tag>
              </div>
            </div>


          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, InfoFilled, Lock } from '@element-plus/icons-vue'
import { getUserProfile, updateUserProfile, checkProfileCompleteness, getSecurityInfo, getProfileSuggestions } from '@/api/userProfile'
import { useUserInfoStore } from '@/stores/userInfo'
import { getAvatarUrl } from '@/utils/avatar'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 表单引用
const profileFormRef = ref()
// 数据
const saving = ref(false)

const uploadAction = ref('/api/file/upload.do') // 头像上传接口

// 个人信息表单
const profileForm = reactive({
  username: '',
  realName: '',
  phone: '',
  avatarUrl: '',
  idCard: '',
  driverLicense: ''
})

// 自定义验证函数
const validatePhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入手机号'))
    return
  }
  // 如果是脱敏数据（包含*），跳过验证
  if (value.includes('*')) {
    callback()
    return
  }
  // 验证完整手机号格式
  if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'))
    return
  }
  callback()
}

const validateIdCard = (rule, value, callback) => {
  if (!value) {
    callback()
    return
  }
  // 如果是脱敏数据（包含*），跳过验证
  if (value.includes('*')) {
    callback()
    return
  }
  // 验证完整身份证号格式
  if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) {
    callback(new Error('请输入正确的身份证号'))
    return
  }
  callback()
}

const validateDriverLicense = (rule, value, callback) => {
  if (!value) {
    callback()
    return
  }
  // 如果是脱敏数据（包含*），跳过验证
  if (value.includes('*')) {
    callback()
    return
  }
  // 验证完整驾驶证号格式
  if (!/^[0-9]{12}$/.test(value)) {
    callback(new Error('请输入正确的驾驶证号'))
    return
  }
  callback()
}

// 表单验证规则
const profileRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, validator: validatePhone, trigger: 'blur' }
  ],
  idCard: [
    { validator: validateIdCard, trigger: 'blur' }
  ],
  driverLicense: [
    { validator: validateDriverLicense, trigger: 'blur' }
  ]
}

// 完整性信息
const completenessInfo = reactive({
  completeness: 0,
  completedFields: 0,
  totalFields: 6,
  missingFields: []
})

// 安全信息
const securityInfo = reactive({
  securityLevel: 0,
  securityLevelText: '',
  phone: '',
  hasIdCard: false,
  hasDriverLicense: false
})

// 建议列表
const suggestions = ref([])

// 编辑状态
const isEditingIdCard = ref(false)
const isEditingDriverLicense = ref(false)

// 原始数据存储
const originalIdCard = ref('')
const originalDriverLicense = ref('')

// 脱敏显示方法
const maskIdCard = (idCard) => {
  if (!idCard || idCard.length < 8) return idCard
  return idCard.substring(0, 6) + '****' + idCard.substring(idCard.length - 4)
}

const maskDriverLicense = (license) => {
  if (!license || license.length < 8) return license
  return license.substring(0, 4) + '****' + license.substring(license.length - 4)
}

// 身份证编辑相关方法
const editIdCard = () => {
  isEditingIdCard.value = true
  profileForm.idCard = originalIdCard.value
}

const handleIdCardFocus = () => {
  if (!isEditingIdCard.value) {
    isEditingIdCard.value = true
    profileForm.idCard = originalIdCard.value
  }
}

const handleIdCardBlur = () => {
  if (profileForm.idCard) {
    originalIdCard.value = profileForm.idCard
    profileForm.idCard = maskIdCard(profileForm.idCard)
  }
  isEditingIdCard.value = false
}

// 驾驶证编辑相关方法
const editDriverLicense = () => {
  isEditingDriverLicense.value = true
  profileForm.driverLicense = originalDriverLicense.value
}

const handleDriverLicenseFocus = () => {
  if (!isEditingDriverLicense.value) {
    isEditingDriverLicense.value = true
    profileForm.driverLicense = originalDriverLicense.value
  }
}

const handleDriverLicenseBlur = () => {
  if (profileForm.driverLicense) {
    originalDriverLicense.value = profileForm.driverLicense
    profileForm.driverLicense = maskDriverLicense(profileForm.driverLicense)
  }
  isEditingDriverLicense.value = false
}

// 方法
const loadUserProfile = async () => {
  try {
    console.log('开始加载用户资料...')
    console.log('当前用户信息:', userInfoStore.userInfo)

    // 获取当前登录用户ID
    const userId = userInfoStore.userInfo?.id
    if (!userId) {
      ElMessage.error('用户未登录')
      router.push('/login')
      return
    }

    console.log('获取用户资料，用户ID:', userId)

    // 从后端API获取真实用户数据
    const response = await getUserProfile({
      userId: userId
    })

    console.log('用户资料API响应:', response)

    if (response.success && response.data) {
      const userData = response.data

      console.log('API返回的完整用户数据:', userData)
      console.log('用户数据字段详情:', {
        username: userData.username,
        realName: userData.realName,
        phone: userData.phone,
        avatarUrl: userData.avatarUrl,
        idCardEncrypted: userData.idCardEncrypted,
        driverLicenseEncrypted: userData.driverLicenseEncrypted
      })

      // 存储原始数据
      originalIdCard.value = userData.idCardEncrypted || ''
      originalDriverLicense.value = userData.driverLicenseEncrypted || ''

      console.log('存储的原始数据:', {
        originalIdCard: originalIdCard.value,
        originalDriverLicense: originalDriverLicense.value
      })

      // 显示脱敏数据
      Object.assign(profileForm, {
        username: userData.username || '',
        realName: userData.realName || '',
        phone: userData.phone ? userData.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '',
        avatarUrl: userData.avatarUrl || '',
        idCard: userData.idCardEncrypted ? maskIdCard(userData.idCardEncrypted) : '',
        driverLicense: userData.driverLicenseEncrypted ? maskDriverLicense(userData.driverLicenseEncrypted) : ''
      })

      console.log('设置表单数据:', profileForm)
      console.log('脱敏后的身份证:', profileForm.idCard)
      console.log('脱敏后的驾驶证:', profileForm.driverLicense)

      // 加载数据后重新计算完整性和安全信息
      await loadCompleteness()
      await loadSecurityInfo()
    } else {
      ElMessage.error('获取用户资料失败：' + (response.message || '未知错误'))
    }

  } catch (error) {
    ElMessage.error('加载用户信息失败')
    console.error('加载用户信息失败:', error)
  }
}

const loadCompleteness = async () => {
  try {
    // 动态计算完整性
    const fields = [
      { key: 'username', name: '用户名', value: profileForm.username },
      { key: 'realName', name: '真实姓名', value: profileForm.realName },
      { key: 'phone', name: '手机号', value: profileForm.phone },
      { key: 'idCard', name: '身份证号', value: originalIdCard.value },
      { key: 'driverLicense', name: '驾驶证号', value: originalDriverLicense.value },
      { key: 'avatarUrl', name: '头像', value: profileForm.avatarUrl }
    ]

    const completedFields = fields.filter(field => field.value && field.value.trim() !== '')
    const missingFields = fields.filter(field => !field.value || field.value.trim() === '').map(field => field.name)

    const completeness = Math.round((completedFields.length / fields.length) * 100)

    Object.assign(completenessInfo, {
      completeness: completeness,
      completedFields: completedFields.length,
      totalFields: fields.length,
      missingFields: missingFields
    })

    // 动态生成建议
    suggestions.value = []
    if (!originalIdCard.value || originalIdCard.value.trim() === '') {
      suggestions.value.push({
        field: 'idCard',
        title: '实名认证',
        description: '完成实名认证可享受更多服务',
        priority: 'high'
      })
    }
    if (!originalDriverLicense.value || originalDriverLicense.value.trim() === '') {
      suggestions.value.push({
        field: 'driverLicense',
        title: '驾驶证认证',
        description: '上传驾驶证信息以便租车服务',
        priority: 'high'
      })
    }

  } catch (error) {
    console.error('加载完整性信息失败:', error)
  }
}

const loadSecurityInfo = async () => {
  try {
    // 根据实际数据判断认证状态
    const hasIdCard = originalIdCard.value && originalIdCard.value.trim() !== ''
    const hasDriverLicense = originalDriverLicense.value && originalDriverLicense.value.trim() !== ''
    const hasPhone = profileForm.phone && profileForm.phone.trim() !== ''

    // 计算安全等级
    let securityLevel = 0
    let securityItems = 0

    if (hasPhone) {
      securityLevel += 40
      securityItems++
    }
    if (hasIdCard) {
      securityLevel += 30
      securityItems++
    }
    if (hasDriverLicense) {
      securityLevel += 30
      securityItems++
    }

    let securityLevelText = '低'
    if (securityLevel >= 80) {
      securityLevelText = '高'
    } else if (securityLevel >= 50) {
      securityLevelText = '中'
    }

    Object.assign(securityInfo, {
      securityLevel: securityLevel,
      securityLevelText: securityLevelText,
      phone: profileForm.phone ? profileForm.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '未绑定',
      hasIdCard: hasIdCard,
      hasDriverLicense: hasDriverLicense
    })

  } catch (error) {
    console.error('加载安全信息失败:', error)
  }
}

const saveProfile = async () => {
  if (!profileFormRef.value) return
  
  try {
    await profileFormRef.value.validate()
    
    saving.value = true
    
    // 调用更新API，使用原始数据
    const response = await updateUserProfile({
      userId: userInfoStore.userInfo?.id || '', // 从用户状态获取当前登录用户ID
      realName: profileForm.realName,
      phone: profileForm.phone,
      avatarUrl: profileForm.avatarUrl,
      idCard: originalIdCard.value,
      driverLicense: originalDriverLicense.value
    })

    // 由于request拦截器已经处理了成功响应，这里直接处理成功逻辑
    ElMessage.success('个人信息保存成功')

    // 更新用户信息存储（同步头像到右上角）
    if (userInfoStore.userInfo) {
      userInfoStore.setUserInfo({
        ...userInfoStore.userInfo,
        avatar: profileForm.avatarUrl,
        realName: profileForm.realName
      })
    }

    // 重新加载完整性和安全信息
    await loadCompleteness()
    await loadSecurityInfo()
    
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      ElMessage.error('保存失败')
      console.error('保存个人信息失败:', error)
    }
  } finally {
    saving.value = false
  }
}

const handleAvatarSuccess = (response, file) => {
  console.log('头像上传成功回调:', response, file)
  if (response.success) {
    // FileController 返回的文件名在 message 字段中
    const fileName = response.message
    profileForm.avatarUrl = fileName
    ElMessage.success('头像上传成功')

    // 立即更新用户信息存储（同步头像到右上角）
    if (userInfoStore.userInfo) {
      userInfoStore.setUserInfo({
        ...userInfoStore.userInfo,
        avatar: fileName
      })
    }
  } else {
    ElMessage.error('头像上传失败：' + (response.message || '未知错误'))
  }
}

const handleAvatarError = (error, file) => {
  console.error('头像上传失败:', error, file)
  ElMessage.error('头像上传失败，请重试')
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const getProgressColor = (percentage) => {
  if (percentage >= 80) return '#67c23a'
  if (percentage >= 60) return '#e6a23c'
  return '#f56c6c'
}

const getSuggestionType = (priority) => {
  const typeMap = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'info'
  }
  return typeMap[priority] || 'info'
}

const getSecurityType = (level) => {
  if (level >= 80) return 'success'
  if (level >= 60) return 'warning'
  return 'danger'
}

// 初始化
onMounted(() => {
  loadUserProfile() // 这个方法内部会调用 loadCompleteness 和 loadSecurityInfo
})
</script>

<style scoped>
.profile-management {
  padding: 20px;
}

.profile-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3,
.card-header h4 {
  margin: 0;
  color: #303133;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409eff;
}

.avatar-tips p {
  margin: 5px 0;
  color: #606266;
}

.tips-text {
  font-size: 12px;
  color: #909399;
}

.completeness-content,
.security-content {
  padding: 10px 0;
}

.progress-section {
  margin-bottom: 20px;
}

.progress-text {
  text-align: center;
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.missing-fields h5,
.suggestions h5 {
  margin: 15px 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.missing-fields ul {
  margin: 0;
  padding-left: 20px;
}

.missing-fields li {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}

.suggestion-item {
  margin-bottom: 15px;
}

.suggestion-desc {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 12px;
}

.security-level {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.security-items {
  margin-bottom: 20px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.security-item:last-child {
  border-bottom: none;
}

.security-value {
  color: #606266;
  font-size: 14px;
}

.security-actions {
  text-align: center;
}
</style>
